package com.liliya.config;


import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

/**
 * @Description TODO
 * @Author hhy
 * @Date 2021/1/7 10:28
 */
@WebFilter(filterName = "loginFilter", urlPatterns = "/*", initParams = {
        @WebInitParam(name = "loginUI", value = "/admin/login"),
        @WebInitParam(name = "loginProcess", value = "admin/adminlogin.jsp"),
        @WebInitParam(name = "img",value = "/img"),
        @WebInitParam(name = "common",value = "/common"),
        @WebInitParam(name = "js",value = "/js"),
        @WebInitParam(name = "encoding", value = "utf-8") })
public class LoginFilter implements Filter {
    private FilterConfig config;

    @Override
    public void init(FilterConfig config) throws ServletException {
        this.config = config;
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        String loginUI = config.getInitParameter("loginUI");
        String loginProcess = config.getInitParameter("loginProcess");
        String encoding = config.getInitParameter("encoding");
        String img = config.getInitParameter("img");
        String common = config.getInitParameter("common");
        String js = config.getInitParameter("js");


        Enumeration<String> initPs = config.getInitParameterNames();

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        request.setCharacterEncoding(encoding);

        String requestURI = request.getRequestURI();
        System.out.println("本次访问了："+requestURI);
        if (requestURI.contains(loginUI)||requestURI.contains(loginProcess)||requestURI.contains(img)||requestURI.contains(common)||requestURI.contains(js)){
            //如果请求的url是放行的url那就过
            chain.doFilter(request,response);
        }else {
            if (request.getSession().getAttribute("user")==null){
                response.sendRedirect(request.getContextPath()+"/"+loginProcess);
            }else {
                //如果有用户对象那就放行
                chain.doFilter(request,response);
            }
        }
    }

    @Override
    public void destroy() {
        this.config = null;
    }
}
